#include "DevCfg.h"
#include "FileSys.h"
#include "Utility.h"
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QFileSystemWatcher>

static const QString s_cfg_name = QStringLiteral("dev.cfg");

DevCfg::DevCfg()
{
    loadCfgs();
}

DevCfg::~DevCfg()
{
    delete m_cfgObj;
}

DevCfg& DevCfg::instance()
{
    static DevCfg s_cfg;
    return s_cfg;
}

bool DevCfg::getInt(const QString& key, int& v, int dft)
{
    if(m_cfgObj && m_cfgObj->contains(key))
    {
        v = (*m_cfgObj)[key].toInt(dft);
        return true;
    }
        
    v = dft;
    return false;
}

bool DevCfg::getString(const QString& key, QString& v, QString dft)
{
    if(m_cfgObj && m_cfgObj->contains(key))
    {
        v = (*m_cfgObj)[key].toString(dft);
        return true;
    }

    v = dft;
    return false;
}

bool DevCfg::getBoolean(const QString& key, bool& v, bool dft)
{
    if(m_cfgObj && m_cfgObj->contains(key))
    {
        v = (*m_cfgObj)[key].toBool(dft);
        return true;
    }

    v = dft;
    return false;
}

void DevCfg::loadCfgs()
{
    delete m_cfgObj;
    m_cfgObj = nullptr;

    QString devCfgFilePath = FileSys::instance()->userCfgDir() + "/" + s_cfg_name;

    QJsonDocument doc = CoreUtility::openJsonDoc(devCfgFilePath);
    if(!doc.isNull())
    {
        m_cfgObj = new QJsonObject(doc.object());
    }
}
